package com.etung.iot.demo.handler;

import com.alibaba.fastjson.JSONObject;
import com.etung.iot.demo.configs.TopicConfig;
import com.etung.iot.demo.constant.CommonConstant;
import com.etung.iot.demo.constant.WebSocketConstant;
import com.etung.iot.demo.dao.BoxStatusMapper;
import com.etung.iot.demo.dao.UserMapper;
import com.etung.iot.demo.dao.VariantMapper;
import com.etung.iot.demo.modles.BoxStatus;
import com.etung.iot.demo.services.VariantMgrService;
import com.etung.iot.demo.services.impl.VariantMgrServiceImp;
import com.etung.iot.demo.utils.RedisUtil;
import com.etung.iot.demo.utils.SpringContextUtils;
import com.etung.iot.demo.websocket.MyWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Handler(TopicConfig.SYS_TOPIC)
@Slf4j
public class SystemTopicHandler implements TopicHandler{
    @Autowired
    private BoxStatusMapper boxStatusMapper;
    @Autowired
    private MyWebSocket myWebSocket;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private VariantMapper variantMapper;
    @Autowired
    private UserCacheUtil userCacheUtil;


    @Override
    public void handler(String topic,String payload) {
        log.info("playload:"+ payload);
        BoxStatus boxStatus = new BoxStatus();
        JSONObject jsonObject = JSONObject.parseObject(payload);
        boolean isConnected = true;
        if(topic.endsWith("disconnected")){
            isConnected = false;
        }
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if("username".equals(entry.getKey())){
                boxStatus.setImei(entry.getValue().toString());
            }
            if("ts".equals(entry.getKey())){
                boxStatus.setTime(new Date(Long.parseLong(entry.getValue().toString())));
                if (isConnected){
                    boxStatus.setStatus(String.valueOf(CommonConstant.CONNECTED));
                }else{
                    boxStatus.setStatus(String.valueOf(CommonConstant.DISCONNECTED));
                }

            }
        }
        if(!boxStatus.getImei().isEmpty()){
            JSONObject content = new JSONObject();
            content.put("msg_type",TopicConfig.MESSAGE_TYPE_BOX_STATUS);
            content.put("imei",boxStatus.getImei());
            content.put("status",boxStatus.getStatus());

            //离线处理缓存并推送
            if(String.valueOf(CommonConstant.DISCONNECTED).equals(boxStatus.getStatus())){
                List<String> varIdList = variantMapper.selectVarIdByImei(boxStatus.getImei());
                if(varIdList != null && varIdList.size() > 0){
                    varIdList.forEach(varId->{
                        String cacheKey = CommonConstant.REAL_DATA_CACHE_PREFIX + boxStatus.getImei() +'_' +  varId;
                        redisUtil.del(cacheKey);
                    });
                }
                String uid = userCacheUtil.getUid(boxStatus.getImei());
                if(!StringUtils.isEmpty(uid)){
                    myWebSocket.pushRealData(uid,content.toJSONString());
                }
            }

            boxStatusMapper.insert(boxStatus);
        }
    }
}
